package console4.widgets;

import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseWheelListener;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

import console4.util.StringUtil;

public class ConsoleTextPrompt {
	
	private StyledText textPane;
	private LinkedList<String> oldCommands=new LinkedList<String>();
	private int oldCommandIndex=-1;
	//dispose
	private Color backgroundColor=new Color(Display.getCurrent(),  0,  0,  0);
	private Color errorColor=	  new Color(Display.getCurrent(),255,  0,  0);
	private Color textColor=	  new Color(Display.getCurrent(),255,255,255);
	private Font  textFont =	  new Font(Display.getCurrent(), "Lucida Console", 12, SWT.NONE);
	private ConsoleTab consoleTab;

	public ConsoleTextPrompt(Composite parent, final ConsoleTab consoleTab) {
		this.consoleTab=consoleTab;
		textPane = new StyledText(parent, SWT.SINGLE | SWT.WRAP);
		textPane.setFocus();
		textPane.setEditable(true);
		textPane.setBackground(backgroundColor);
		textPane.setForeground(textColor);
		textPane.setFont(textFont);
		textPane.addTraverseListener(new TraverseListener() {
			@Override
			public void keyTraversed(TraverseEvent e) {
				if(e.character=='\t') {
					e.doit=true;
					e.detail=SWT.TRAVERSE_NONE;
					String txt=textPane.getText();
					int pathPos;
					if(StringUtil.countOccurrences(txt, '"')%2==1)
						pathPos=txt.lastIndexOf('"');
					else
						pathPos=txt.lastIndexOf(' ');
					String fullPath=txt.substring(pathPos+1);
					File newPath=getNextFileForTab(new File(fullPath));
					if(newPath!=null) {
						textPane.setText(txt.substring(0, pathPos+1)+newPath.toString());
						textPane.setCaretOffset(textPane.getText().length());
					}
				}
			}
		});
		textPane.addDisposeListener(new DisposeListener() {
			@Override
			public void widgetDisposed(DisposeEvent e) {
				backgroundColor.dispose();
				textColor.dispose();
				errorColor.dispose();
				textFont.dispose();
			}
		});
		textPane.addMouseWheelListener(new MouseWheelListener() {
			@Override
			public void mouseScrolled(MouseEvent e) {
				consoleTab.scrollBy(e.count);
			}
		});
		textPane.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(e.character=='\r') {
					e.doit=false;
					if(oldCommands.isEmpty() || !oldCommands.getFirst().equals(textPane.getText()))
						oldCommands.addFirst(textPane.getText());
					consoleTab.execute(textPane.getText());
					oldCommandIndex=-1;
					textPane.setText("");
				}
				//arrow up
				else if(e.keyCode==16777217) {
					e.doit=false;
					if(oldCommandIndex+1<oldCommands.size()) {
						oldCommandIndex++;
						textPane.setText(oldCommands.get(oldCommandIndex));
					}
				}
				//arrow down
				else if(e.keyCode==16777218) {
					e.doit=false;
					if(oldCommandIndex-1>=0) {
						oldCommandIndex--;
						textPane.setText(oldCommands.get(oldCommandIndex));
					}
					else {
						oldCommandIndex=-1;
						textPane.setText("");
					}
				}
			}
		});
	}
	
	public void setLayoutData(Object layoutData) {
		textPane.setLayoutData(layoutData);
	}

	public Control getComponent() {
		return textPane;
	}
	
	private File getNextFileForTab(File path) {
		File fullPath=path;
		if(!fullPath.isAbsolute())
			fullPath=new File(consoleTab.getCurrentPath(),fullPath.toString());
		/*if(fullPath.isDirectory() && path.toString().endsWith(File.separator)) {
			String[] children=fullPath.list();
			if(children.length>0) {
				Arrays.sort(children);
				return new File(path,children[0]); 
			}
			else
				return null;
		}
		else {*/
			String pathEnd=fullPath.getName();
			File parentFolder=fullPath.getParentFile();
			String[] children=parentFolder.list();
			if(children!=null) {
				Arrays.sort(children);
				//check if equals
				for(int i=0;i<children.length;i++) {
					if(children[i].equalsIgnoreCase(pathEnd)) {
						if(i<children.length-1)
							return new File(path.getParentFile(),children[i+1]);
						else
							return new File(path.getParentFile(),children[0]);
					}	
				}
				for(int i=0;i<children.length;i++) {
					if(children[i].toLowerCase().startsWith(pathEnd.toLowerCase()))
						return new File(path.getParentFile(),children[i]);
				}
				return new File(path.getParentFile(),children[0]);
			}
			return null;
		//}
	}

	public void appendPath(String data) {
		if(data.contains(" "))
			textPane.append('"'+data+'"');
		else
			textPane.append(data);
	}

	public List<String> getOldCommands() {
		return oldCommands;
	}

	public void setOldCommands(List<String> c) {
		oldCommands=new LinkedList<>(c);
	}
}
